package com.cloud.sso.service;

import com.cloud.sso.common.config.SSOProperty;
import com.cloud.sso.common.constant.UserState;
import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.common.page.AppPageInfo;
import com.cloud.sso.common.util.SnowFlakeUtil;
import com.cloud.sso.dto.UpdatePasswordDto;
import com.cloud.sso.dto.UserQueryDto;
import com.cloud.sso.dto.UserSaveDto;
import com.cloud.sso.entity.User;
import com.cloud.sso.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SSOProperty ssoProperty;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 分页查询用户
     *
     * @param queryDto
     * @return
     */
    public AppPageInfo queryByPage(UserQueryDto queryDto) {

        //计算分页相关属性
        queryDto.setStartIndex();

        List<User> userList = userMapper.queryUserPage(queryDto);
        Integer count = userMapper.getCount(queryDto);

        AppPageInfo pageInfo = new AppPageInfo(userList, count, queryDto.getPageNum(), queryDto.getPageSize());


        return pageInfo;
    }

    /**
     * 根据用户名搜索用户
     * @param userName
     * @return
     */
    public List<User> search(String userName) {
        return userMapper.searchByUserName(userName);
    }

    /**
     * 保存用户
     *
     * @param userDto
     */
    public void save(UserSaveDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        try {
            if (StringUtils.isEmpty(userDto.getId())) {
                user.setId(new SnowFlakeUtil().nextStringId());
                user.setState(UserState.ENABLE);
                //如果密码为空，设置初始化密码sc123456
                if (StringUtils.isEmpty(userDto.getPassword())) {
                    user.setPassword(ssoProperty.getDefaultPassword());
                }
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                userMapper.insert(user);
            } else {
                userMapper.updateById(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(e.getMessage());
        }
    }

    public User get(String id) {
        User user = userMapper.selectById(id);
        user.setPassword(null);
        return user;
    }

    public List<User> listByOrg(String orgId) {
        Map<String, Object> param = new HashMap<>();
        param.put("org_id", orgId);

        return userMapper.selectByMap(param);
    }

    /**
     * 删除用户
     *
     * @param userId
     */
    public void delete(String userId) {
        try {
            userMapper.deleteById(userId);
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        }
    }

    /**
     * 重置密码
     *
     * @param userId
     */
    public void resetPassword(String userId) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                throw new AppException("找不到该用户");
            }
            user.setPassword(passwordEncoder.encode(ssoProperty.getDefaultPassword()));

            userMapper.updateById(user);
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        }
    }

    /**
     * 更新用户密码
     *
     * @param dto
     */
    public void updatePassword(UpdatePasswordDto dto) {
        if (dto.getUserId() == null || dto.getNewPassword() == null || dto.getOldPassword() == null) {
            throw new AppException("信息不完善");
        }
        try {
            User user = userMapper.selectById(dto.getUserId());
            if (user == null) {
                throw new AppException("找不到该用户");
            }

            if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
                throw new AppException("原密码输入错误");
            }
            if (passwordEncoder.matches(dto.getNewPassword(), user.getPassword())) {
                throw new AppException("新密码不能与原密码相同");
            }
            user.setPassword(passwordEncoder.encode(dto.getNewPassword()));
            userMapper.updateById(user);
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        }
    }

    /**
     * 更新用户状态
     *
     * @param userId
     */
    public void updateState(String userId) {
        try {
            User user = userMapper.selectById(userId);

            if (user == null) {
                throw new AppException("找不到该用户");
            }
            UserState state = user.getState() == UserState.ENABLE ? UserState.DISABLE : UserState.ENABLE;
            user.setState(state);

            userMapper.updateById(user);
        } catch (Exception e) {
            throw new AppException(e.getMessage());
        }
    }

}
